package com.supor.aiot.common.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseNfcActivity;
import com.supor.aiot.common.helper.ActivityHelper;

import java.util.HashMap;
import java.util.List;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 动态权限申请页面，页面为透明，数据交互完销毁页面 <br>
 * 作者: lei <br>
 * 日期: 2020/10/17 <br>
 */
public class SuporPermissionActivity extends BaseNfcActivity {
    private RxPermissions rxPermissions;
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    private AppBasicDialog commonDialog;
    // param: 1一键登录请求权限|2-小程序请求权限|3-本地分享请求权限|4一键登录请求权限，非全屏
    int param = 0;
    int permissionType = 0;
    List<String> permissionArray = null;
    String[] permissionStr = null;
    HashMap map;

    @Override
    protected int resourceId() {
        return R.layout.activity_nfc;
    }

    @Override
    public void initData() {
        super.initData();
        rxPermissions = new RxPermissions(this);
        process(getIntent());
    }

    @SuppressLint("CheckResult")
    private void process(Intent intent) {
        if (intent == null) {
            finish();
            return;
        }

        param = intent.getIntExtra(Constants.Key.param_params, 0);
        permissionType = intent.getIntExtra(Constants.Key.param_type, 0);
        map = (HashMap) intent.getSerializableExtra(Constants.Key.param_msg);
        permissionArray = intent.getStringArrayListExtra(Constants.Key.param_list);
        permissionStr = new String[permissionArray.size()];
        permissionArray.toArray(permissionStr);

        processPermissions();
    }

    @SuppressLint({"CheckResult", "AutoDispose"})
    private void processPermissions() {
        if (permissionArray.size() == 0) {
            Logc.i("permission is empty");
            if (param == 1) {
                ToastUtils.getInstance().showCustomToast("请先同意授权");
            } else if (param == 2) {
                SuporPresenter.getInstance().reportPermission(2, permissionType);
            }
            finish();
            return;
        }
        rxPermissions.request(permissionStr)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        //表示用户同意权限
                        Logc.i("permission request: success");
                        if (param == 1) {
                            SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                        } else if (param == 2) {
                            SuporPresenter.getInstance().reportPermission(1, permissionType);
                        } else if (param == 3) {
                            ThreadUtils.execute(()
                                    -> SuporPresenter.getInstance().getShareHelper()
                                    .shareMsg(new JSONObject(map)));
                        } else if (param == 4) {
                            SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                        }
                        finish();
                    } else {
                        //表示用户不同意权限
                        Logc.i("permission request: failed");
                        // 不再弹框App的提示框 --2021/01/04
                        // showDialog();
                        if (param == 1) {
                            ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation(this);
                        } else if (param == 2) {
                            SuporPresenter.getInstance().reportPermission(2, permissionType);
                        } else if (param == 4) {
                            ARouter.getInstance().build(PathUrl.PATH_DIALOG_LOGIN)
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation(this);
                        }
                        finish();
                    }
                });
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return false;
    }

    /**
     * 显示缺失权限提示
     */
    protected void showDialog() {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        if (permissionType == 1) {
            builder.setTitle(R.string.permission_camera_title);
            builder.setMessage(R.string.permission_camera_msg);
        } else if (permissionType == 2)  {
            builder.setTitle(R.string.permission_storage_title);
            builder.setMessage(R.string.permission_storage_msg);
        } else if (permissionType == 3)  {
            builder.setTitle(R.string.permission_phone_title);
            builder.setMessage(R.string.permission_phone_msg);
        }
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
            if (param == 1) {
                ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(this);
            } else if (param == 2) {
                SuporPresenter.getInstance().reportPermission(2, permissionType);
            } else if (param == 4) {
                ARouter.getInstance().build(PathUrl.PATH_DIALOG_LOGIN)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(this);
            }
            finish();
        });
        builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
            ActivityHelper.startAppSettings(SuporPermissionActivity.this, Constants.REQUEST_CODE);
            dialog.dismiss();
        });
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logc.i("onActivityResult resultCode: " + resultCode
                + ", requestCode: " + requestCode);
        PermissionsChecker mPermissionsChecker = new PermissionsChecker(this);

        if (mPermissionsChecker.lacksPermissions(permissionStr)) {
            if (param == 1) {
                ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(this);
            } else if (param == 2) {
                SuporPresenter.getInstance().reportPermission(2, permissionType);
            } else if (param == 4) {
                ARouter.getInstance().build(PathUrl.PATH_DIALOG_LOGIN)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(this);
            }
        } else {
            if (param == 1) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
            } else if (param == 2) {
                SuporPresenter.getInstance().reportPermission(1, permissionType);
            } else if (param == 3) {
                ThreadUtils.execute(()
                        -> SuporPresenter.getInstance().getShareHelper()
                        .shareMsg(new JSONObject(map)));
            } else if (param == 4) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
            }
        }
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.tranlate_out);
    }
}